<template>
  <el-row :gutter="15" class="bottom" :style="bodyStyle">
    <el-col :span="6">
      <div class="calendar">
        <el-calendar v-model="dateValue" :style="borderStyle">
          <div
            slot="dateCell"
            slot-scope="{ data }"
            @click="querySchedule(data.day)"
          >
            <p :class="data.isSelected ? 'is-selected' : ''">
              {{
                data.day
                  .split("-")
                  .slice(2)
                  .join("-")
              }}
            </p>
          </div>
        </el-calendar>
      </div>
    </el-col>
    <el-col :span="17">
      <div class="schContent" :style="borderStyle">
        <el-table
          :data="tableData"
          style="width: 100%"
          :style="bodyStyle"
          :row-style="bodyStyle"
          :header-cell-style="bodyStyle"
          @cell-mouse-enter="changeStyle"
        >
          <template slot="empty">
            <p class="emptyText" :style="bodyStyle" />
          </template>

          <!-- @row-click="navigatorEdit" -->
          <el-table-column prop="title" label="日程标题">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.title" placement="top">
                <div
                  style="
                overflow: hidden;
                display:-webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                white-space: normal;
              "
                >
                  {{ scope.row.title }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="content" label="日程内容">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.content" placement="top">
                <div
                  style="
                overflow: hidden;
                display:-webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                white-space: normal;
              "
                >
                  {{ scope.row.content }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column> -->
          <el-table-column prop="fqrname" label="日程发起人" width="80" />
          <el-table-column prop="kssj" label="日程开始时间" />
          <el-table-column prop="jssj" label="日程结束时间" />
          <el-table-column prop="rcjb" label="优先级" width="80" />
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="navigatorEdit(scope.row)"
              >查看</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, tableData)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          slot="left-footer"
          :page-size.sync="page.pageSize"
          :page-count="5"
          :total="page.total"
          :current-page.sync="page.pageNo"
          style="margin-top: 8px;"
          :style="bodyStyle"
          layout="total, prev, pager, next"
          background
          @current-change="handleCurrentChange"
        />
        <el-dialog :visible.sync="infoVisiable" :close-on-click-modal="false">
          <el-form ref="form" :model="form" label-width="100px" disabled>
            <el-form-item label="日程标题" prop="title">
              <el-input v-model="form.title" disabled />
            </el-form-item>
            <el-form-item label="日期">
              <el-col :span="11">
                <el-form-item prop="kssj">
                  <el-date-picker
                    v-model="form.kssj"
                    placeholder="开始时间"
                    type="datetime"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item
                  prop="jssj"
                ><el-date-picker
                  v-model="form.jssj"
                  placeholder="结束时间"
                  type="datetime"
                  style="width: 100%"
                /></el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item label="是否公开" prop="sfgk">
              <el-switch v-model="form.sfgk" />
            </el-form-item>
            <el-form-item label="日程级别" prop="rcjb">
              <el-radio-group v-model="form.rcjb1">
                <el-radio label="1">一般日程</el-radio>
                <el-radio label="2">重要日程</el-radio>
                <el-radio label="3">紧急日程</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="日程描述" prop="content">
              <el-input v-model="form.content" type="textarea" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <!-- <el-button type="primary" @click="addSchedule('form')">
              保存
            </el-button> -->
            <el-button @click="infoVisiable = false">
              关闭
            </el-button>
          </div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { queryAllScheduleByPage, deleteObject } from '@/api/schedule/schedule';
import { template } from '@/mixins/template';
export default {
  mixins: [template],
  props: {
    temp: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      show: true,
      currentDate: '',
      dateValue: new Date(),
      dialogVisible: false,
      infoVisiable: false,
      scheduleList: [],
      resultTime: [],
      tableData: [],
      form: {
        fqrname: '',
        title: '',
        kssj: '',
        jssj: '',
        sfgk: true,
        rcjb1: '',
        content: ''
      },
      initPage: { pageNo: 0, pageSize: 6, total: 0 },
      page: { pageNo: 0, pageSize: 6, total: 0 },
      params: { page: 0, size: 6, queryUser: '', datetime: '' },
      initparams: { page: 0, size: 6, queryUser: '', datetime: '' },
      sffqr: false,
      row: '',
      column: '',
      borderStyle: {},
      bodyStyle: {}
    };
  },
  computed: {
    themes() {
      return this.$store.getters.theme;
    }
  },
  watch: {
    themes: {
      handler(val, oldVal) {
        // this.borderStyle.borderRadius = val.bkdx;
        this.borderStyle.border = '1px solid ' + val.bkys;
        this.borderStyle.boxShadow = '0 2px 4px rgba(0, 0, 0, .12)';
        this.borderStyle.background = val.columnGroundColor;
        this.borderStyle.color = val.fontColor;
        this.bodyStyle.background = val.columnGroundColor;
        this.bodyStyle.color = val.fontColor;
        this.borderStyle = Object.assign({}, this.borderStyle);
        this.bodyStyle = Object.assign({}, this.bodyStyle);
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    }
  },
  mounted() {
    window.addEventListener(
      'storage',
      e => {
        // e只是一个传参
        // 获取被修改的键值
        if (e.key == 'themes') {
          // 分别打印会发现内容一致
          // console.log(e.storageArea.themes);
          console.log('当前主题', localStorage.themes);
          this.$store
            .dispatch('GetThemes')
            .then(res => {
              return true;
            })
            .catch(error => {
              console.log(error);
            });
          // this.$store.getters.theme = JSON.parse(localStorage.themes);
        }
      },
      false
    );
  },
  created() {
    this.initData();
  },

  methods: {
    changeStyle(row, column, cell, event) {
      this.row = row;
      this.column = column;
    },
    // tableRowClassName({ row, rowIndex }) {
    //   if (this.row == row.row) {
    //     return "background-color:#000;";
    //   }
    //   return "";
    // },
    handleDelete(index, data, rows) {
      var userid = this.$store.getters.user.username;
      if (data.fqr == userid) {
        console.log(data.id);
        if (data.id !== null && undefined !== data.id) {
          // 单个删除
          this.$confirm('此操作将永久删除该' + ', 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            (async() => {
              try {
                const delResult = await deleteObject({ id: data.id });
                console.log(delResult + '删除结果');
                if (delResult.state == 200) {
                  this.$message.success('删除成功！');
                  this.$emit('handleDelete');
                  rows.splice(index, 1);
                } else {
                  this.$message.error('删除失败！');
                }
              } catch (error) {
                console.log(error);
              }
            })();
          });
        }
      }
    },
    setIsSelectedValue(date) {
      this.dateValue = date;
    },

    getCurrentDate() {
      const currentDate = new Date();
      const getDay = currentDate.getDate();
      // 月份需要加 1
      const getMonth = currentDate.getMonth() + 1;
      const getYear = currentDate.getFullYear();
      var HH = currentDate.getHours();
      var mm = currentDate.getMinutes();
      mm = mm > 9 ? mm : '0' + mm.toString();
      var ss = currentDate.getSeconds();
      const date = `${getYear}-${getMonth}-${getDay} 00:00:00`;
      return date;
    },
    // 初始化查询当天的日程信息
    initData() {
      const userid = this.$store.getters.user.username;
      console.log('当前页：' + this.page.pageNo);
      const currrentDate = this.getCurrentDate();
      this.currentDate = currrentDate;
      this.initparams.queryUser = userid;
      this.initparams.datetime = currrentDate;

      (async() => {
        try {
          const initQueryResult = await queryAllScheduleByPage(this.initparams);
          var result = initQueryResult.content;
          var code = initQueryResult.state;
          var length = initQueryResult.totalElements;
          var currentSize = this.initPage.pageSize;
          const itemLength = currentSize <= length ? currentSize : length;
          this.page.total = 0;
          if (code === 200 && length > 0) {
            this.page.total = length;
            this.tableData = [];
            for (var i = 0; i < itemLength; i++) {
              // console.log(result.data[i]);
              var sch = {
                id: result[i].id,
                fqr: result[i].fqr,
                rcjb:
                  result[i].rcjb == 1
                    ? '一般'
                    : result[i].rcjb == 2
                      ? '重要'
                      : '紧急',
                title: result[i].title,
                content: result[i].content,
                fqrname: result[i].name,
                kssj: result[i].kssj,
                jssj: result[i].jssj,
                sfgk: result[i].sfgk
              };
              this.tableData.push(sch);

              // console.log(this.tableData);
            }
            this.params.page = 0;
          }
        } catch (error) {
          console.log(error);
        }
      })();
    },
    // 切换当前页显示的数据条数，执行方法
    // handleSizeChange(val) {
    //   console.log(`每页 ${val} 条`);
    //   this.page.pageSize = val;
    //   this.initData();
    // },

    handleCurrentChange(val) {
      console.log(`当前页: ${val} , 当前日期：${this.currentDate}`);
      this.page.pageNo = val;
      this.initparams.page = val - 1;
      this.params.page = val - 1;
      this.initData();
      this.querySchedule(this.currentDate);
    },

    // 疑问：如何在切换页数的时候调用本方法(因为方法中需要传递时间参数)
    // 根据日期查询日程信息

    querySchedule(data) {
      this.currentDate = data;
      const userid = this.$store.getters.user.username;
      console.info('当前日期' + data);
      if (data !== null && undefined !== data) {
        var time = `${data} 00:00:00`;
        this.params.queryUser = userid;
        this.params.datetime = time;
        // 获取当前分页参数中的每页条数
        var currentQuerySize = this.page.pageSize;

        (async() => {
          try {
            const queryResult = await queryAllScheduleByPage(this.params);
            var result = queryResult.content;

            var result = queryResult.content;
            var code = queryResult.state;
            var length = queryResult.totalElements;
            // 查看当前分页参数中每页条数的默认值是否大于数据的总条数，如果大于 就直接取总条数，否则就取设置的默认值
            const queryCurrentLength =
              currentQuerySize <= length ? currentQuerySize : length;
            console.log(length + '总条数');
            this.tableData = [];
            this.page.total = 0;
            if (code == 200 && length > 0) {
              this.page.total = length;
              for (var i = 0; i < queryCurrentLength; i++) {
                var sch = {
                  id: result[i].id,
                  fqr: result[i].fqr,
                  rcjb:
                    result[i].rcjb == 1
                      ? '一般'
                      : result[i].rcjb == 2
                        ? '重要'
                        : '紧急',
                  title: result[i].title,
                  content: result[i].content,
                  fqrname: result[i].name,
                  kssj: result[i].kssj,
                  jssj: result[i].jssj,
                  sfgk: result[i].sfgk
                };
                this.tableData.push(sch);
              }
              this.params.page = 0;
            }
          } catch (error) {
            console.log(error);
          }
        })();
      }
    },
    navigatorEdit(row) {
      this.infoVisiable = true;
      this.form = row;
      var type = row.rcjb;
      if (type == '一般') {
        this.form.rcjb1 = '1';
      } else if (type == '重要') {
        this.form.rcjb1 = '2';
      } else {
        this.form.rcjb1 = '3';
      }
      console.log(row);
    },
    addSchedule(formName) {
      const userid = this.$store.getters.user.username;
      this.form.fqr = userid;
      // this.form.sysOrganizations = this.treeValue.join(';')

      this.$refs[formName].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          (async() => {
            try {
              const result = await saveSchedule(this.form);
              console.log(result);

              if (result.state === 200) {
                loading.close();
                this.$message({
                  message: '保存成功',
                  type: 'success',
                  customClass: 'messageIndex'
                });
              }

              this.$emit('initData');
              this.dialogFormVisible = false;
            } catch (error) {
              loading.close();
              this.$message({
                message: '保存失败！',
                type: 'warning',
                customClass: 'messageIndex'
              });
            }
          })();
        }
      });
    }
  }
};
</script>
<style scoped>
.bottom {
  display: flex;
}
.calendar ::v-deep .el-calendar {
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  box-sizing: border-box;
}

.calendar ::v-deep .el-button--mini {
  padding: 5px 8px;
}

.calendar ::v-deep .el-calendar__body {
  padding: 12px 20px 22px;
}
.calendar ::v-deep .el-calendar-table .el-calendar-day {
  height: 40px;
  text-align: center;
  padding: 1px;
}
.calendar ::v-deep .el-calendar-table .el-calendar-day:hover {
  background-color: #009988;
}
.calendar ::v-deep .el-calendar-table td.is-today {
  color: #000;
}
.calendar ::v-deep .el-calendar-table td.is-selected {
  background-color: #009988;
}

.calendar ::v-deep .el-calendar-table tr td {
  border: none;
}

.calendar ::v-deep .el-calendar__header {
  height: 50px;
  color: #fff;
  background: #009988;
  padding: 12px 10px;
}
.calendar ::v-deep .el-calendar__title {
  color: #fff;
}

.schContent {
  padding-top: 1px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  box-sizing: border-box;
  border-radius: 5px;
  height: 100%;
}
/* el-table列数据为空自动显示-- */
.cell:empty::before {
  content: "--";
  color: gray;
}

.schContent
  ::v-deep
  .el-table--enable-row-hover
  .el-table__body
  tr:hover
  > td.el-table__cell {
  background: #9ba9a8;
}
.schContent ::v-deep .el-table__row:hover > td {
  background-color: transparent;
  /* background: #000; */
}

.schContent ::v-deep .el-input.is-disabled .el-input__inner {
  color: #000;
}

.schContent ::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #000;
}

.schContent ::v-deep .el-table__header-wrapper thead > tr > th {
  background-color: #f4f4f4;
  padding: 13px 0;
}
.schContent ::v-deep .cell {
  white-space: nowrap;
}

.schContent ::v-deep .el-switch .el-switch__core {
  border-color: #000;
  background-color: #000;
}
.schContent ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner {
  background-color: #000;
  border-color: #000;
}
.schContent ::v-deep .el-input__prefix {
  display: none;
}
.schContent ::v-deep .el-input--prefix .el-input__inner {
  padding-left: 15px;
  padding-right: 15px;
}
</style>
